package com.raincat.tools.nettools;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.util.Locale;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2020/03/23
 *     desc   : 下载
 *     version: 1.0
 * </pre>
 */
class ConnectDownload extends Connect {
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    private int size = 0;
    private Intent service;

    @Override
    void init(Request request) {
        super.init(request);

        service = new Intent(request.context.get(), DownloadService.class);
        service.putExtra("url", request.url);
        service.putExtra("resId", request.notificationResId);
        request.context.get().startService(service);

        registerBroadcastReceiver(request);
    }

    private void registerBroadcastReceiver(final Request request) {
        broadcastManager = LocalBroadcastManager.getInstance(request.context.get());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadService.DOWNLOAD_FAILURE);
        intentFilter.addAction(DownloadService.DOWNLOAD_START);
        intentFilter.addAction(DownloadService.DOWNLOAD_SUCCESS);
        intentFilter.addAction(DownloadService.DOWNLOAD_STATUS);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (intent.getAction()) {
                    case DownloadService.DOWNLOAD_FAILURE:
                        unregisterBroadcastReceiver();
                        if (mProgressDialog != null)
                            mProgressDialog.dismiss();
                        request.back.error(-1, "DOWNLOAD ERROR!");
                        break;
                    case DownloadService.DOWNLOAD_SUCCESS:
                        String path = "{\"path\":\"" + intent.getStringExtra("path") + "\"}";
                        unregisterBroadcastReceiver();
                        if (mProgressDialog != null)
                            mProgressDialog.dismiss();
                        request.back.result(path);
                        break;
                    case DownloadService.DOWNLOAD_START:
                        if (request.isShowDownDialog) {
                            size = intent.getIntExtra("size", 0);
                            createDialog(request, request.context.get(), size);
                        }
                        break;
                    case DownloadService.DOWNLOAD_STATUS:
                        if (request.isShowDownDialog) {
                            int length = intent.getIntExtra("length", 0);
                            refreshDialog(length, size);
                        }
                        break;
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        if (broadcastReceiver != null && broadcastManager != null)
            broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    private void createDialog(Request request, final Context context, int size) {
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        mProgressDialog.setCancelable(false);// 设置是否可以通过点击Back键取消
        mProgressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        mProgressDialog.setTitle("下载中...");
        mProgressDialog.setMax(size);
        mProgressDialog.setProgressNumberFormat(String.format(Locale.getDefault(), "%.2fM/%.2fM", 0.0f, size / 1024.0 / 1024.0));
        if (request.isDialogCancelable)
            mProgressDialog.setButton2("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    context.stopService(service);
                    unregisterBroadcastReceiver();
                }
            });
        mProgressDialog.show();
    }

    private void refreshDialog(int length, int size) {
        if (mProgressDialog != null) {
            mProgressDialog.setProgress(length);
            mProgressDialog.setProgressNumberFormat(String.format(Locale.getDefault(), "%.2fM/%.2fM", length / 1024.0 / 1024.0, size / 1024.0 / 1024.0));
        }
    }
}
